import React, { useContext, useMemo, useState } from 'react';
import { Button, Space, message } from 'antd';
import { WorkflowHndTaskBtn } from '@/components/WorkflowCommonCopy';
import { AllBtnsConfig } from '../mconfig';
import { NeedControllerContext } from '../common';
import { getNeedinvalidService } from '../services/DetailOAService';
import { RollbackOutlined } from '@ant-design/icons';
import { FGLDSH_STATE, JZLZ_STATE, purchaseNeedCategory, SHZ_STATE, XQBZ_STATE, ZRBGH_STATE } from '../common/Format';
import { BZZ_CHECKSTATE, SHTH_CHECKSTATE, formatDecimal } from '../../Acommon';
import { DiffOutlined } from '@ant-design/icons';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import { getPosIDs, getTenantID, getUserID } from '@/utils';
import moment from 'moment';
import { ILoadMapTypeAll } from '@/common';
export const DetailInfoBottomBtnView: React.FC = () => {
  /** 引入上下文 */
  const {
    taskId,
    NumGatherMemo,
    curRes,
    pageType,
    needDetailInfo,
    needForm,
    tableData,
    oldNeedInfo,
    styleFixCls,
    reloadDetail,
    fetchEditNeed,
    setOAMessageRun,
  } = useContext(NeedControllerContext);

  /** 签发提示框 */
  const [openTipInfoModal, setOpenTipInfoModal] = useState<Record<string, any>>({
    checkRowObj: {},
    showModal: false,
    tipType: null, // delete:删除   revoke:撤销
  });

  /** 按钮是否显示 */
  const allBtnsMemo = useMemo(() => {
    return AllBtnsConfig(curRes, needDetailInfo, false, needForm, oldNeedInfo, pageType);
  }, [curRes, needDetailInfo, needForm, oldNeedInfo, pageType]);

  /** 签发按钮关闭 */
  const tipOnClose = () => {
    setOpenTipInfoModal({
      checkRowObj: {},
      showModal: false,
      tipType: null,
    });
  };

  /** 提示弹框回调 */
  const tipModalCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadDetail();
      tipOnClose();
    } else {
      message.error(res?.msg);
    }
  };

  const onSubmit = () => {
    tableData?.forEach((item) => {
      item.expectNum = formatDecimal(item?.expectNum);
      item.expectPrice = formatDecimal(item?.expectPrice);
    });

    let paramsObj = {
      ...needDetailInfo,
      purchaseNeedMaterials: tableData,
    };
    fetchEditNeed(paramsObj);
  };

  /** 引入撤销接口 */
  const { getNeedinvalidRun } = getNeedinvalidService(tipModalCallback);

  const isShowEidtBtn = useMemo(() => {
    if (
      needDetailInfo?.state == JZLZ_STATE() &&
      needDetailInfo?.checkState == BZZ_CHECKSTATE() &&
      needDetailInfo?.applyerID == getUserID() &&
      needDetailInfo?.applyPositionID == getPosIDs()
    )
      return true;

    return false;
  }, [needDetailInfo?.state, needDetailInfo?.checkState]);

  return (
    <div className={`${styleFixCls}infoViewOA-bottomBtnBox-spaceItemBox`}>
      <Space>
        {isShowEidtBtn && (
          <Button
            type="primary"
            // icon={<DiffOutlined />}
            onClick={() => {
              /** 校验论证意见是否上传 */
              for (let i = 0; i < tableData?.length; i++) {
                if (tableData[i]?.needProofFlag && tableData[i]?.needProofFlag == 1) {
                  if (!tableData[i]?.needProofURL) {
                    message.warn(`提示：${tableData[i]?.fullName || '--'}，缺少需求论证意见！`);
                    return;
                  }
                }

                if (tableData[i]?.needImportFlag && tableData[i]?.needImportFlag == 1) {
                  if (!tableData[i]?.needImportURL) {
                    message.warn(`提示：${tableData[i]?.fullName || '--'}，缺少进口专业人员论证意见！`);
                    return;
                  }
                }

                if (tableData[i]?.needSingleFlag && tableData[i]?.needSingleFlag == 1) {
                  if (!tableData[i]?.needSingleURL) {
                    message.warn(`提示：${tableData[i]?.fullName || '--'}，缺少单一来源论证意见！`);
                    return;
                  }
                }
              }
              onSubmit();
            }}
          >
            暂存
          </Button>
        )}

        {/* 流程节点弹框 */}
        <WorkflowHndTaskBtn
          flowDetailInfo={needDetailInfo}
          reloadCallback={reloadDetail}
          requestController={'purchaseNeedController'}
          isAloneSubmit={
            (needDetailInfo?.state == JZLZ_STATE() && needDetailInfo?.checkState == BZZ_CHECKSTATE()) ||
            (needDetailInfo?.state == ZRBGH_STATE() && needDetailInfo?.checkState == BZZ_CHECKSTATE()) ||
            (needDetailInfo?.state == XQBZ_STATE() && needDetailInfo?.checkState == SHTH_CHECKSTATE())
          }
          clickBeforeFun={() => {
            return new Promise((resolve) => {
              // 获取当前的状态 是集中论证
              if (needDetailInfo?.state == JZLZ_STATE() && needDetailInfo?.checkState == BZZ_CHECKSTATE() && curRes?.['/purchaseNeedController/edit']) {
                /** 校验论证意见是否上传 */
                for (let i = 0; i < tableData?.length; i++) {
                  if (tableData[i]?.needProofFlag && tableData[i]?.needProofFlag == 1) {
                    if (!tableData[i]?.needProofURL) {
                      message.warn(`提示：${tableData[i]?.fullName || '--'}，缺少需求论证意见！`);
                      return;
                    }
                  }

                  if (tableData[i]?.needImportFlag && tableData[i]?.needImportFlag == 1) {
                    if (!tableData[i]?.needImportURL) {
                      message.warn(`提示：${tableData[i]?.fullName || '--'}，缺少进口专业人员论证意见！`);
                      return;
                    }
                  }

                  if (tableData[i]?.needSingleFlag && tableData[i]?.needSingleFlag == 1) {
                    if (!tableData[i]?.needSingleURL) {
                      message.warn(`提示：${tableData[i]?.fullName || '--'}，缺少单一来源论证意见！`);
                      return;
                    }
                  }
                }
                resolve(onSubmit());
              } else if (needDetailInfo?.state == ZRBGH_STATE() && needDetailInfo?.checkState == BZZ_CHECKSTATE() && curRes?.['/purchaseNeedController/edit']) {
                if (NumGatherMemo?.allNum == NumGatherMemo?.yiNum) {
                  resolve(true);
                } else {
                  message.warn(`提示：还有标的未审核 , 待审核数量为: ${NumGatherMemo?.daiNum}`);
                }
              } else {
                resolve(null);
              }
            });
          }}
          clickSuccessFun={() => {
            setOAMessageRun({
              id: taskId,
              isRemark: 2,
              viewType: 1,
              endTime: moment()?.format('YYYY-MM-DD HH:mm:ss'),
            });
          }}
          flowBusinessType={purchaseNeedCategory()}
          applyHeader={'apply'}
          revokeRequestUrl={'/purchaseNeedController/invalid'}
          revokeRequestState={`${getTenantID()}${ILoadMapTypeAll.NEED_STATE}`}
          isShowRevokeStateList={[SHZ_STATE(), JZLZ_STATE(), ZRBGH_STATE()]}
          revokeTitle={openTipInfoModal?.checkRowObj?.needName}
          revokeSuccessCallback={reloadDetail}
        />

        {/* {allBtnsMemo?.revokeBtnDiv && (
          <Button
            type="primary"
            danger
            // icon={<RollbackOutlined />}
            onClick={() => {
              setOpenTipInfoModal({
                checkRowObj: needDetailInfo,
                showModal: true,
                tipType: 'revoke',
              });
            }}
          >
            撤销
          </Button>
        )} */}
      </Space>

      {/* {allBtnsMemo?.allBtnDiv && (

      )} */}

      {/* 提示框
      {openTipInfoModal?.showModal && (
        <TipsErrorModalNew
          ref={tipErrorModalRef}
          modalLoading={false}
          onClose={tipOnClose}
          modalOnOK={
            openTipInfoModal?.tipType == 'revoke'
              ? () => {
                  invalidModalOnOk(openTipInfoModal?.checkRowObj, getNeedinvalidRun);
                }
              : () => {}
          }
          tipTextColor="#000"
          modalTip={renderTipName(openTipInfoModal?.tipType, openTipInfoModal?.checkRowObj)}
        />
      )} */}

      {/* 撤销 */}
      {openTipInfoModal?.showModal && (
        <RevokeModal
          resObj={openTipInfoModal?.checkRowObj}
          revokeRequestUrl={'/purchaseNeedController/invalid'}
          onClose={() => setOpenTipInfoModal({})}
          reqBody={{ state: XQBZ_STATE() }}
          modalTip={
            <div style={{ color: '#000' }}>
              确认是否撤销【<span style={{ color: 'red' }}>{openTipInfoModal?.checkRowObj?.needName}</span>】的审核, 撤销后可重新提交！
            </div>
          }
          reloadRequest={reloadDetail}
        />
      )}
    </div>
  );
};
